package com.xsomnus.java_basic.juc;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author @叶小夏
 * @since 2019/7/27 0027 15:25
 * - 才需学也,学需静也/非淡泊无以明志，非宁静无以致远
 */
public class TimerTest {

    interface Dispatcher {
        void notify(String msg);
    }

    static class DispatcherImpl implements Dispatcher {

        @Override
        public void notify(String msg) {
            System.out.println("收到了消息[" + msg + "]");
        }
    }

    public static void main(String[] args) {
        final Timer timer = new Timer();
        final int MaxRetry = 5;
        final String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println(now + " start");
        timer.schedule(new TimerTask() {
            int retryTimes = 0;
            Dispatcher dispatcher;

            @Override
            public void run() {
                System.out.println("begin...");
                if (retryTimes++ < MaxRetry) {
                    System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " 第【" + retryTimes + "】次重发消息");
                } else {
                    System.out.println("已超过最大重试次数, 关闭定时任务...");
                    if (dispatcher != null) {
                        dispatcher.notify("失败");
                    }
                    this.cancel();
                }

            }
        }, 1000, 1000);
    }
}
